// pages/membership_level/membership_level.js
const request = require('../../utils/promise.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userId: null,
    userInfo: null,
    levelIndex: 0,
    levelArr: ['普通用户', '社员', '决策社员'],
    levelName: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.userId = options.userId;
    this.reqUserInfo();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面被用户分享时执行
   */
  onShareAppMessage() {
    return {
      title: '用户角色修改'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '用户角色修改'
    }
  },

  /**
   * 获取用户数据
   */
  reqUserInfo() {
    request.GET('/user/userInfo', {userId: this.data.userId}).then(res => {
      // console.log(res)
      if (res.data.resCode==200) {
        const levelIndex = res.data.userInfo['vip']==100? 2: res.data.userInfo['vip'];
        const levelName = this.data.levelArr[levelIndex];

        this.setData({
          userInfo: res.data.userInfo,
          levelIndex: levelIndex,
          levelName: levelName
        })
      } else {
        wx.showToast({
          title: '获取数据异常',
          icon: 'error',
          duration: 1500
        })
      }
    })
  },

  /**
   * picker 修改
   */
  bindPickerChange(e) {
    const name = this.data.levelArr[e.detail.value];
    this.setData({
      levelIndex: e.detail.value,
      levelName: name
    })
  },

  /**
   * 点击保存
   */
  clickSave() {

    var vipLevel = this.data.levelIndex;
    if (vipLevel==2) {
      vipLevel = 100;
    }

    wx.showToast({
      title: '保存中',
      icon: 'loading',
      duration: 30000,
      mask: true,
    })

    request.GET('/user/updateVipLevel', {userId: this.data.userId, vipLevel: vipLevel}).then(res => {
      wx.hideToast();
      if (res.data.resCode==200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1000,
          mask: true,
        })

        setTimeout(function(){
          wx.navigateBack({
            delta: 1,
          })
        }, 1000)
      } else {
        wx.showToast({
          title: '保存异常',
          icon: 'error',
          mask: true
        })
      }
    })
  },

})